package com.walming.generator.support.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.walming.generator.common.cache.DictCacheUtils;
import com.walming.generator.common.constant.Constants;
import com.walming.generator.common.core.domain.Ztree;
import com.walming.generator.common.exception.BusinessException;
import com.walming.generator.common.utils.StringUtils;
import com.walming.generator.copycat.mybatisplus.service.impl.ServiceImpl;
import com.walming.generator.support.domain.SysDictData;
import com.walming.generator.support.domain.SysDictType;
import com.walming.generator.support.mapper.SysDictTypeMapper;
import com.walming.generator.support.query.DictTypeQuery;
import com.walming.generator.support.service.ISysDictDataService;
import com.walming.generator.support.service.ISysDictTypeService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 字典 业务层处理
 *
 * @author walming
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService {

    @Resource
    private ISysDictDataService dictDataService;

    /**
     * 项目启动时，初始化字典到缓存
     */
    //@PostConstruct
    public void init() {
        List<SysDictType> dictTypeList = this.selectDictTypeAll();
        for (SysDictType dictType : dictTypeList) {
            List<SysDictData> dictDataList = dictDataService.selectDictDataByType(dictType.getDictType());
            DictCacheUtils.setDictCache(dictType.getDictType(), dictDataList);
        }
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param typeQuery 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public PageInfo<SysDictType> selectDictTypeList(DictTypeQuery typeQuery) {
        return this.startPage(typeQuery);
    }

    /**
     * 获取所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll() {
        return this.list();
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    @Cacheable(value = DictCacheUtils.SYS_DICT_CACHE, key = "'sys_dict:' + #dictType")
    public List<SysDictData> selectDictDataByType(String dictType) {
        return dictDataService.selectDictDataByType(dictType);
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeById(Long dictId) {
        return this.getById(dictId);
    }

    /**
     * 根据字典类型查询信息
     *
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeByType(String dictType) {
        LambdaQueryWrapper<SysDictType> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysDictType::getDictType, dictType);
        return this.getOne(queryWrapper);
    }

    /**
     * 批量删除字典类型
     *
     * @param ids 需要删除的数据
     * @return 结果
     */
    @Override
    public int deleteDictTypeByIds(List<Long> ids) {
        for (Long dictId : ids) {
            SysDictType dictType = selectDictTypeById(dictId);
            if (dictDataService.countDictDataByType(dictType.getDictType()) > 0) {
                throw new BusinessException(String.format("%1$s已分配, 不能删除", dictType.getDictName()));
            }
        }
        int count = this.baseMapper.deleteBatchIds(ids);
        if (count > 0) {
            DictCacheUtils.clearDictCache();
        }
        return count;
    }

    /**
     * 清空缓存数据
     */
    @Override
    public void clearCache() {
        DictCacheUtils.clearDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dictType 字典类型信息
     * @return 结果
     */
    @Override
    public int insertDictType(SysDictType dictType) {
        int row = this.baseMapper.insert(dictType);
        if (row > 0) {
            DictCacheUtils.clearDictCache();
        }
        return row;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dictType 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDictType(SysDictType dictType) {
        SysDictType oldDict = this.getById(dictType.getDictId());
        // 同步修改字典数据类型
        dictDataService.updateDictDataType(oldDict.getDictType(), dictType.getDictType());
        int row = this.baseMapper.updateById(dictType);
        if (row > 0) {
            DictCacheUtils.clearDictCache();
        }
        return row;
    }

    /**
     * 校验字典类型是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public String checkDictTypeUnique(SysDictType dict) {
        long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        SysDictType dictType = this.selectDictTypeByType(dict.getDictType());
        if (StringUtils.isNotNull(dictType) && dictType.getDictId() != dictId) {
            return Constants.DICT_TYPE_NOT_UNIQUE;
        }
        return Constants.DICT_TYPE_UNIQUE;
    }

    /**
     * 查询字典类型树
     *
     * @param typeQuery 字典类型
     * @return 所有字典类型
     */
    @Override
    public List<Ztree> selectDictTree(DictTypeQuery typeQuery) {
        List<Ztree> zTrees = new ArrayList<>();
        List<SysDictType> dictList = this.list(typeQuery);
        for (SysDictType dict : dictList) {
            if (Constants.DICT_NORMAL.equals(dict.getStatus())) {
                Ztree ztree = new Ztree();
                ztree.setId(dict.getDictId());
                ztree.setName(transDictName(dict));
                ztree.setTitle(dict.getDictType());
                zTrees.add(ztree);
            }
        }
        return zTrees;
    }

    public String transDictName(SysDictType dictType) {
        return "(" + dictType.getDictName() + ")" + "&nbsp;&nbsp;&nbsp;" + dictType.getDictType();
    }

}
